'use strict';
const {
	timestampToFormatInfo
} = require('common-date');
const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
const wmzAlipaySdk = uniCloud.importObject('wmz-alipay-sdk')
exports.main = async (event, context) => {
	let rechargeDatas = await db.collection('wmz-entitlement-order').where({
		status: '已付款',
		msg_status: dbCmd.exists(false)
	}).limit(10).orderBy('create_time', 'desc').get()
	rechargeDatas = rechargeDatas.data
	console.log(rechargeDatas.length)
	let appletInfo
	for (var i in rechargeDatas) {
		appletInfo = await db.collection('wmz-applet-info').doc(rechargeDatas[i].app_id).get()
		appletInfo = appletInfo.data[0]
		if (appletInfo) {
			console.log(appletInfo.alipay.buy_msg)
			if (appletInfo.alipay.buy_msg) {
				let params = {
					app_id: rechargeDatas[i].app_id,
					url: 'alipay.merchant.order.sync',
					biz_content: {
						out_biz_no: rechargeDatas[i]._id,
						buyer_id: rechargeDatas[i].ali_user_id,
						amount: rechargeDatas[i].money,
						pay_amount: rechargeDatas[i].money,
						trade_no: rechargeDatas[i].trade_no,
						order_create_time: timestampToFormatInfo(rechargeDatas[i].create_time).formatTime,
						order_modified_time: timestampToFormatInfo(rechargeDatas[i].pay_time).formatTime,
						order_type: "SERVICE_ORDER",
						ext_info: [{
							"ext_key": "tiny_app_id",
							"ext_value": appletInfo.alipay.auth_app_id
						}, {
							"ext_key": "merchant_order_status",
							"ext_value": "FINISHED"
						}, {
							"ext_key": "merchant_biz_type",
							"ext_value": "VIRTUAL_GOODS_ORDER"
						}, {
							"ext_key": "merchant_order_link_page",
							"ext_value": "/pages/tabbar/user"
						}],
						item_order_list: [{
							item_name: appletInfo.alipay.buy_msg,
							quantity: 1,
							unit_price: rechargeDatas[i].money
						}]
					}
				}

				let res = await wmzAlipaySdk.alipayRequestCommon(params)
				if (res.code === 200) {
					await db.collection('wmz-entitlement-order').doc(rechargeDatas[i]._id).update({
						msg_status: true
					})
				} else {
					await db.collection('wmz-entitlement-order').doc(rechargeDatas[i]._id).update({
						msg_status: "error"
					})
				}
			}
		}
	}
	return event
};